//
//  MSPasswordView.m
//  MuRenHe
//
//  Created by mls on 2021/5/19.
//

#import "MSPasswordView.h"

#define PASSWORD_NUMBER 6

@interface MSPasswordView ()
<
UITextFieldDelegate
>

@property (nonatomic, assign) MSPasswordViewType    type;
@property (nonatomic, strong) UILabel               *titleLabel;
@property (nonatomic, strong) MSPasswordTextField   *passwordTextField;
@property (nonatomic, strong) UILabel               *errorMsgLabel;
@property (nonatomic, strong) UILabel               *forgetPasswordLabel;
@property (nonatomic, strong) UIView                *showPasswordView;
@property (nonatomic, strong) UIButton              *doneBtn;

@end

@implementation MSPasswordView

#pragma mark - event
/** 取消输入密码 */
- (void)cancelInputPassword
{
    if ([self.delegate respondsToSelector:@selector(ms_passwordViewDidCancel:)])
    {
        [self.delegate ms_passwordViewDidCancel:self];
    }
}
/** 确定 */
- (void)done
{
    if ([self.delegate respondsToSelector:@selector(ms_passwordViewDidComplete:)])
    {
        [self.delegate ms_passwordViewDidComplete:self];
    }
}
/** 忘记密码 */
- (void)forgetPayPassword
{
    if ([self.delegate respondsToSelector:@selector(ms_forgetPasswordInPasswordView:)])
    {
        [self.delegate ms_forgetPasswordInPasswordView:self];
    }
}

- (void)textFieldEditionChanged:(UITextField *)textField
{
    if (textField.text.length > PASSWORD_NUMBER)
    {
        textField.text = [textField.text substringToIndex:6];
    }
    
    self.errorMsgLabel.text = @"";
    if (textField.text.length == PASSWORD_NUMBER)
    {
        if (self.type == MSPasswordViewTypePay)
        {
//            if ([AccountModel.account.payPasswd isEqualToString:textField.text])
//            {
//                // 支付密码正确
//                self.password1 = textField.text;
//            }
//            else
//            {
//                // 支付密码错误
//                self.passwordTextField.text = @"";
//                self.errorMsgLabel.text = @"支付密码错误";
//            }
            self.password1 = textField.text;
        }
        else
        {
            if (ms_stringIsEmpty(self.password1))
            {
                // 记录首次密码并清空输入框，以便进行二次确认输入
                self.password1 = textField.text;
                self.passwordTextField.text = @"";
            }
            else
            {
                if ([self.password1 isEqualToString:textField.text])
                {
                    // 设置密码两次输入密码一致
                    self.password2 = textField.text;
                    self.errorMsgLabel.text = @"";
                }
                else
                {
                    // 设置密码两次输入密码不一致
                    self.passwordTextField.text = @"";
                    self.errorMsgLabel.text = @"两次输入密码不一致";
                }
            }
        }
    }
    
    [self updateShowPasswordView];
}


#pragma mark - UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (string.length == 1)
    {
        NSString *regex = @"[0-9]";
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        
        return [predicate evaluateWithObject:string];
    }
    else if (string.length > 1)
    {
        return NO;
    }
    else
    {
        return YES;
    }
}


#pragma mark - private method

- (void)updateShowPasswordView
{
    for (int i = 0; i < PASSWORD_NUMBER; i++)
    {
        UILabel *label = [self.showPasswordView viewWithTag:100 + i];
        if (i < self.passwordTextField.text.length)
        {
            label.text = @"·";
        }
        else
        {
            label.text = @"";
        }
    }
    
    self.titleLabel.text = self.type == MSPasswordViewTypeSetUp ? (ms_stringIsEmpty(self.password1) ? @"请设置支付密码" : @"请再次输入支付密码") : @"支付密码";
    self.doneBtn.hidden = self.type == MSPasswordViewTypeSetUp && ms_stringIsEmpty(self.password1);
    self.doneBtn.enabled = (self.type == MSPasswordViewTypeSetUp && [self.password1 isEqualToString:self.password2]) || (self.type == MSPasswordViewTypePay && self.password1.length == 6);
}

- (void)ms_addSubViews
{
    self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.65];
    CGFloat width = 564 * MS_ADAPTATION_RATIO;
    CGFloat height = 87 * MS_ADAPTATION_RATIO;
    
    UIView *view = [[UIView alloc] init];
    [view ms_makeChains:^(MSChainMaker * _Nonnull make) {
        
        make
        .ms_backgroundColor(UIColor.whiteColor)
        .ms_cornerRadii(26 * MS_ADAPTATION_RATIO)
        .ms_addToSuperView(self);
    }];
    
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(228 * MS_ADAPTATION_RATIO);
        make.width.mas_equalTo(628 * MS_ADAPTATION_RATIO);
        make.height.mas_equalTo(488 * MS_ADAPTATION_RATIO);
        make.centerX.equalTo(self);
    }];
    
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [closeBtn setImage:MS_IMAGE_NAMED(@"close")
              forState:UIControlStateNormal];
    [closeBtn addTarget:self
                 action:@selector(cancelInputPassword)
       forControlEvents:UIControlEventTouchUpInside];
    
    [view addSubview:closeBtn];
    
    [closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.left.equalTo(view);
        make.width.height.mas_equalTo(92 * MS_ADAPTATION_RATIO);
    }];
    
    [view addSubview:self.titleLabel];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(70 * MS_ADAPTATION_RATIO);
        make.centerX.equalTo(view);
    }];
    
    [view addSubview:self.passwordTextField];
    
    [self.passwordTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(210 * MS_ADAPTATION_RATIO);
        make.width.mas_equalTo(width);
        make.height.mas_equalTo(height);
        make.centerX.equalTo(view);
    }];
    
    [view addSubview:self.showPasswordView];
    
    [self.showPasswordView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.equalTo(self.passwordTextField);
    }];
    
    for (int i = 0; i < PASSWORD_NUMBER; i++)
    {
        UILabel *label = [UILabel new];
        [label ms_makeChains:^(MSChainMaker * _Nonnull make) {
        
            make
            .ms_tag(100 + i)
            .ms_font(MS_SYSTEM_FONT_OF_SIZE(50))
            .ms_textColor(UIColor.blackColor)
            .ms_textAlignment(NSTextAlignmentCenter)
            .ms_borderSideType(i == PASSWORD_NUMBER - 1 ? MSBorderSideTypeAll : (MSBorderSideTypeTop | MSBorderSideTypeLeft | MSBorderSideTypeBottom))
            .ms_lineColor(MS_HEX_COLOR(0xEEEEEE))
            .ms_lineWidth(1)
            .ms_addToSuperView(self.showPasswordView);
        }];
        
        
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.top.equalTo(self.showPasswordView);
            make.left.mas_equalTo(i * width / PASSWORD_NUMBER);
            make.width.mas_equalTo(width / PASSWORD_NUMBER);
            make.height.mas_equalTo(height);
        }];
    }
    
    [view addSubview:self.errorMsgLabel];
    
    [self.errorMsgLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.passwordTextField.mas_bottom).offset(18 * MS_ADAPTATION_RATIO);
        make.centerX.equalTo(view);
    }];
    
    if (self.type == MSPasswordViewTypePay)
    {
        [view addSubview:self.forgetPasswordLabel];
        
        [self.forgetPasswordLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.top.equalTo(self.passwordTextField.mas_bottom).offset(18 * MS_ADAPTATION_RATIO);
            make.right.equalTo(self.passwordTextField);
            make.height.mas_equalTo(40 * MS_ADAPTATION_RATIO);
        }];
    }
    
    [view addSubview:self.doneBtn];
    
    [self.doneBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.bottom.mas_equalTo(-24 * MS_ADAPTATION_RATIO);
        make.width.mas_equalTo(553 * MS_ADAPTATION_RATIO);
        make.height.mas_equalTo(80 * MS_ADAPTATION_RATIO);
        make.centerX.equalTo(view);
    }];
}


#pragma mark - lazy loading

- (UILabel *)titleLabel
{
    if (!_titleLabel)
    {
        _titleLabel = [UILabel new];
        [_titleLabel ms_makeChains:^(MSChainMaker * _Nonnull make) {
        
            make
            .ms_text(self.type == MSPasswordViewTypeSetUp ? (ms_stringIsEmpty(self.password1) ? @"请设置支付密码" : @"请再次输入支付密码") : @"支付密码")
            .ms_font(MS_SYSTEM_FONT_OF_SIZE(18))
            .ms_textColor(MS_HEX_COLOR(0x1F233B));
        }];
    }
    
    return _titleLabel;
}

- (MSPasswordTextField *)passwordTextField
{
    if (!_passwordTextField)
    {
        _passwordTextField = [[MSPasswordTextField alloc] init];
        [_passwordTextField ms_makeChains:^(MSChainMaker * _Nonnull make) {
        
            make
            .ms_delegate(self)
            .ms_textColor(UIColor.clearColor)
            .ms_tintColor(UIColor.clearColor)
            .ms_keyboardType(UIKeyboardTypeDecimalPad)
            .ms_becomeFirstResponder()
            .ms_addTarget(self, @selector(textFieldEditionChanged:));
        }];
    }
    
    return _passwordTextField;
}

- (UIView *)showPasswordView
{
    if (!_showPasswordView)
    {
        _showPasswordView = [[UIView alloc] init];
        [_showPasswordView ms_makeChains:^(MSChainMaker * _Nonnull make) {
        
            make
            .ms_backgroundColor(UIColor.clearColor)
            .ms_userInteractionEnabled(NO);
        }];
    }
    
    return _showPasswordView;
}

- (UILabel *)errorMsgLabel
{
    if (!_errorMsgLabel)
    {
        _errorMsgLabel = [UILabel new];
        [_errorMsgLabel ms_makeChains:^(MSChainMaker * _Nonnull make) {
        
            make
            .ms_font(MS_SYSTEM_FONT_OF_SIZE(14))
            .ms_textColor(MS_HEX_COLOR(0xF71313));
        }];
    }
    
    return _errorMsgLabel;
}

- (UILabel *)forgetPasswordLabel
{
    if (!_forgetPasswordLabel)
    {
        _forgetPasswordLabel = [UILabel new];
        [_forgetPasswordLabel ms_makeChains:^(MSChainMaker * _Nonnull make) {
        
            make
            .ms_userInteractionEnabled(YES)
            .ms_text(@"忘记密码")
            .ms_font(MS_SYSTEM_FONT_OF_SIZE(14))
            .ms_textColor(MS_HEX_COLOR(0xF71313))
            .ms_addGestureRecognizer([UITapGestureRecognizer new], self, @selector(forgetPayPassword));
        }];
    }
    
    return _forgetPasswordLabel;
}

- (UIButton *)doneBtn
{
    if (!_doneBtn)
    {
        _doneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_doneBtn ms_makeChains:^(MSChainMaker * _Nonnull make) {
            
            make
            .ms_backgroundColor(UIColor.whiteColor)
            .ms_hidden(self.type == MSPasswordViewTypeSetUp)
            .ms_titleFont(MS_SYSTEM_FONT_OF_SIZE(15))
            .ms_title(@"确定", UIControlStateNormal)
            .ms_cornerRadii(5 * MS_ADAPTATION_RATIO)
            .ms_addTarget(self, @selector(done));
        }];
    }
    
    return _doneBtn;
}

- (id)initWithType:(MSPasswordViewType)type
{
    self = [super init];
    if (self) {
        _type = type;
        [self ms_addSubViews];
    }
    
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
